package com.weichen.delivery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weichen.delivery.common.CustomException;
import com.weichen.delivery.common.R;
import com.weichen.delivery.dto.DishDto;
import com.weichen.delivery.entity.Category;
import com.weichen.delivery.entity.Dish;
import com.weichen.delivery.entity.DishFlavor;
import com.weichen.delivery.service.CategoryService;
import com.weichen.delivery.service.DishFlavorService;
import com.weichen.delivery.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;
//    新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

//    菜品信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
//        构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
//        条件构造器
        LambdaQueryWrapper<Dish> queryWrapper =new LambdaQueryWrapper();
//        添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
//        添加排序时间
        queryWrapper.orderByDesc(Dish::getUpdateTime);
//        执行分页查询
        dishService.page(pageInfo,queryWrapper);
//        对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");//pageInfo中的属性records不进行拷贝，records是list整个页面的数据表单
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {//item为遍历的dish对象
            DishDto dishDto =new DishDto();
//            当前dishDto是自己创的，其他的属性都为空，所以要拷贝
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
//            根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

//    根据id查询菜品信息和对应的口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

//    修改菜品
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

//    根据条件查询对应的菜品数据
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
//            条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//             添加条件
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
//        查询起售的（状态为1）
        queryWrapper.eq(Dish::getStatus,1);
        //        添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {//item为遍历的dish对象
        DishDto dishDto =new DishDto();
//            当前dishDto是自己创的，其他的属性都为空，所以要拷贝
        BeanUtils.copyProperties(item,dishDto);
        Long categoryId = item.getCategoryId();//分类id
//            根据id查询分类对象
        Category category = categoryService.getById(categoryId);
        if (category != null){
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
        }
//        当前菜品id
        Long dishId = item.getId();
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }).collect(Collectors.toList());
        return R.success(dishDtoList);

    }



//    菜品启售/停售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status, Long ids) {
        log.info("status:{},ids:{}", status, ids);
        Dish dish = dishService.getById(ids);
        if (dish != null) {
            //直接用它传进来的这个status改就行
            dish.setStatus(status);
            dishService.updateById(dish);
            return R.success("售卖状态修改成功");
        }
        return R.error("系统繁忙，请稍后再试");
    }


/*
//    菜品批量启售/停售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        log.info("status:{},ids:{}", status, ids);
       LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(ids != null, Dish::getId, ids);
        updateWrapper.set(Dish::getStatus, status);
        dishService.update(updateWrapper);
        return R.success("批量操作成功");
    }
*/



//    菜品批量删除
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除的ids：{}", ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        queryWrapper.eq(Dish::getStatus, 1);
        int count = dishService.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("删除列表中存在启售状态商品，无法删除");
        }
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }


}
